package com.huntech.data.sevice;


import cn.hutool.core.util.ZipUtil;
import com.huntech.data.util.ExcelUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.*;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;


@Service
public class FileUploadService {

    public void analysisExeclZip2(MultipartFile file ,HttpServletResponse response) throws IOException {
        Date date = new Date();
        SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd-HHmmss");
        String format =  formater.format(date);
        String originalFilename = file.getOriginalFilename();
        if (null == originalFilename) {
            //log.info("文件类型错误，请上传压缩文件，如以.rar或.zip结尾的文件");
        }
        //log.debug("*** file originalFilename：{}", originalFilename);
        //log.debug("*** file contentType: {}", file.getContentType());
        //log.debug("*** file name: {}", file.getName());
        String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        String basePath = "";
        String uploadPath = "";
        String unpackagePath = "";
        File fileExist;
        File file1;
        if (System.getProperties().getProperty("os.name").contains("Linux")) {
            ApplicationHome home = new ApplicationHome(getClass());
            File file2 = home.getDir();
            basePath = file2.getPath();
            basePath = basePath + "/templateFile/";
            //log.debug("*** app path: {}", basePath);
            uploadPath = basePath + format + "/upload";
            unpackagePath = basePath + format + "/unpackage";
            fileExist = new File(uploadPath);
            file1 = new File(unpackagePath);
            // 文件夹不存在，则新建
            if (!fileExist.exists()) {
                fileExist.mkdirs();
            }
            // 文件夹不存在，则新建
            if (!file1.exists()) {
                file1.mkdirs();
            }
        }
        if (System.getProperties().getProperty("os.name").contains("Windows")) {
            basePath = "E:\\EFileToExcel\\rawData\\";
            uploadPath = basePath + format + "\\upload\\";
            unpackagePath = basePath + format + "\\unpackage\\";
            fileExist = new File(uploadPath);
            file1 = new File(unpackagePath);
            // 文件夹不存在，则新建
            if (!fileExist.exists()) {
                fileExist.mkdirs();
            }
            // 文件夹不存在，则新建
            if (!file1.exists()) {
                file1.mkdirs();
            }
        }
        // 获取文件对象
        File file2 = new File(uploadPath, originalFilename);
        // 完成文件的上传
        file.transferTo(file2);
        //log.debug("*** file2 path: {}", file2.getPath());
        //log.debug("*** file2 AbsolutePath: {}", file2.getAbsolutePath());
        if (fileSuffix.equals(".zip")) {
            // 解压文件  第一个参数包含文件名的全路径，第二个参数：目标文件夹
            ZipUtil.unzip(file2.getPath(), unpackagePath, Charset.forName("GBK"));
        } else if (fileSuffix.equals(".rar")) {
            //RarUtil.unPackRar(file2, unpackagePath);
        }
        //log.info(" 获取到的存储压缩包的路径：{}", uploadPath);
        //log.info(" 解压路径路径：{}", unpackagePath);
        File fileunpack = new File(unpackagePath);
        XSSFWorkbook workbook = null;
        ClassPathResource resource = new ClassPathResource("/templates/duoweidu.xlsx");
        InputStream is = resource.getInputStream();
        workbook = new XSSFWorkbook(is);
        XSSFSheet sheet = null;
        sheet = workbook.getSheetAt(0);
        workbook.setSheetName(0,"列表");

        //设置表格背景色
        XSSFColor xssfColor = new XSSFColor(new Color(255,255,255));
        //添加表头背景
        XSSFCellStyle cellStyle1 = ExcelUtils.createCellStyle(workbook, sheet, (short) 10, false, true, false, false, null, false, true,xssfColor);
        int rownum = 0;
        if (fileunpack.isDirectory()) {
            List<String> filePathList = new ArrayList<>();
            getFileName(fileunpack.list(), unpackagePath ,filePathList);
            for(String filePath : filePathList){
                File fileWpd = new File(filePath);
                String line = "";
                try (BufferedReader br = new BufferedReader(    new InputStreamReader(new FileInputStream(fileWpd) ,"UTF-8"))) {
                    String dateStr = "";
                    int firstRow = rownum;
                    while ((line = br.readLine()) != null){
                        String[] split = line.split("\t");
                        if(split.length <= 1){
                            continue;
                        }
                        if(split[0].startsWith("<!")){
                            for (int i = 0; i < split.length; i++) {
                                if(!split[i].contains("time")){
                                    continue;
                                }
                                dateStr = split[i].replaceAll(".*time='([^']*)'.*", "$1");
                            }
                            continue;
                        }
                        Row nRow0 =  sheet.createRow(rownum);
                        if(split[0].startsWith("@")){
                            nRow0 = sheet.createRow(firstRow);
                            rownum  = firstRow;
                        }
                        for(int j = 0 ;j<split.length ;j++){
                            if(j == 0 && rownum != firstRow){
                                nRow0.createCell(0).setCellValue(dateStr + split[0]);
                                nRow0.getCell(0).setCellStyle(cellStyle1);
                            }
                            else{
                                nRow0.createCell(j).setCellValue(split[j]);
                                nRow0.getCell(j).setCellStyle(cellStyle1);
                            }
                        }
                        rownum++;
                    }
                }

            }
        }
        ExcelUtils.exportExcel(response ,workbook ,format + ".xlsx");
        // 添加清理逻辑
        cleanupFiles(basePath);
    }

    private void getFileName(String[] list, String filePath ,List<String> filePathList){
        if (list != null) {
            for(String fileName : list){
                File file = new File(filePath ,fileName);
                if (file.isDirectory()) {
                    getFileName(file.list(), file.getPath() ,filePathList);
                }else {
                    if (file.getName().contains(".")) {
                        filePathList.add(file.getPath());
                    }
                }
            }
        }
    }

    /**
     * 清理上传和解压的文件
     * @param path 文件路径
     */
    private void cleanupFiles(String path) {
        try {
            // 删除目录及其内容
            deleteDirectory(new File(path));
        } catch (Exception e) {
            // 记录日志（如果配置了日志）
            System.err.println("清理文件时出错: " + e.getMessage());
        }
    }

    /**
     * 递归删除目录及其内容
     * @param directory 要删除的目录
     */
    private void deleteDirectory(File directory) {
        if (directory.exists() && directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        deleteDirectory(file);
                    } else {
                        file.delete();
                    }
                }
            }
            directory.delete();
        }
    }

}
